package cn.micai.base.io;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 描述：
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/20 17:56
 */
public class ArrayOfBytesToFile {

    private static final String UPLOAD_FOLDER = "D:\\test\\";

    public static void main(String [] args) {

        FileInputStream fileInputStream = null;
        try {

            File file = new File("D://newFile.txt");
            byte[] bFile = new byte[(int)file.length()];

            // read file into bytes[]
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bFile);

            // save bytes[] into a file
            writeBytesToFile(bFile, UPLOAD_FOLDER + "test1.txt");
            writeBytesToFileClassic(bFile, UPLOAD_FOLDER + "test2.txt");
            writeBytesToFileNio(bFile, UPLOAD_FOLDER + "test3.txt");

            System.out.println("Done");

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    // Since JDK 7 - try resources
    private static void writeBytesToFile(byte[] bFile, String fileDest) {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(fileDest);
            fileOutputStream.write(bFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Classic, < JDK7
    private static void writeBytesToFileClassic(byte[] bFile, String fileDest) {
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(fileDest);
            fileOutputStream.write(bFile);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // Since JDK 7, NIO
    private static void writeBytesToFileNio(byte[] bFile, String fileDest) {
        try {
            Path path = Paths.get(fileDest);
            Files.write(path, bFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}
